<template>
<!--发微博页面 PostView-->
  <h1>发微博页面</h1>
  <div style="width: 500px;margin: 0 auto;">
    <el-input placeholder="微博正文" v-model="weibo.content"></el-input>
    <!--头像上传开始-->
    <!--action设置上传地址 limit="1"限制上传数量为1
    name="file"设置上传参数名称,后端服务器需要使用相同的名称-->
    <el-upload
        v-model:file-list="fileList"
        action="http://localhost:8080/v1/upload"
        limit="9"
        name="file"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <!--头像上传结束-->
    <el-button type="primary" @click="post"
               style="width: 100px;margin: 10px;font-weight: bold;">发布</el-button>
  </div>
</template>

<script setup>
  import {ref} from "vue";
  import router from "@/router";
  import qs from "qs";
  import axios from "axios";
  import {ElMessage} from "element-plus";

  const fileList = ref([])

  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)

  const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    //1.得到要删除的图片路径
    let imgUrl = uploadFile.response.data;
    //2.向后端发请求删除图片
    axios.post('http://localhost:8080/v1/remove?imgUrl='+imgUrl)
    .then((response)=>{
      if(response.data.code==2001){
        ElMessage.success("服务器删除文件完成!");
      }
    })
  }

  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  }
  const weibo = ref({content:''});
  //发微博方法
  const post = ()=>{
    if(fileList.value.length>0){//>0说明用户传图片了
      let imgUrls = [];//准备空数组,用来存多个图片路径
      for(let file of fileList.value){//遍历响应式变量数组fileList
        let imgUrl = file.response.data;//依次得到每张图片路径,放入imgUrl变量中
        imgUrls.push(imgUrl);//将每个图片路径变量,存入图片数组中
      }
      //微博添加第3个属性imgUrls,值为存放了多张图片路径数组的字符串 a.jpg,b.jpg,c.jpg...
      weibo.value.imgUrls = imgUrls.toString();
    }

    //拿到用户信息,确认登录后才可以发微博
    let user = localStorage.user?JSON.parse(localStorage.user):null;
    if(user==null){
      alert('请先登录!');
      router.push('/login');
      return;
    }
    //给微博设置作者id
    weibo.value.userId= user.id;
    let data = qs.stringify(weibo.value);
    //向后端发请求新增一条微博
    axios.post('http://localhost:8080/v1/weibos/add-new',data)
    .then((response)=>{
      if(response.data.code==2001){
        ElMessage.success('发布成功!');
        router.push('/');
      }
    })
  }
</script>

<style scoped>

</style>